const app = getApp();
const date = new Date();
const baseUrl = app.globalData.baseUrl;
const companyName = app.globalData.companyName;
Page({
  data: {
    userInfo: {},
    month: '月',
    day: '',
    week: '星期',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isShow: false,
    openId: '',
    imgUrls: [],
    imgUrls2: [],
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 500,
    coachList: []
  },
  onLoad: function() {
    const that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          that.setData({
            isShow: true
          })
        }
        if (!res.authSetting['scope.userLocation']) {
          //地理位置授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.getLocation({
                type: 'gcj02',
                success(res) {}
              })
            }
          })
        }
      }
    });

    //设置日期
    const month = (date.getMonth() + 1).toString();
    const day = date.getDate().toString();
    const week = "星期" + "日一二三四五六".charAt(date.getDay());
    this.setData({
      month: month + '月',
      day: day,
      week: week
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo
        });
      }
      if (app.check) {
        app.check();
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo;
          this.setData({
            userInfo: res.userInfo
          });
          if (app.check) {
            app.check();
          }
        }
      })
    }
    that.getCoach();
    that.getClub();
  },
  getCoach: function() {
    const that = this;
    const url = app.globalData.url;
    wx.request({
      url: app.globalData.url + '/coach/coachList',
      data: {
        companyName
      },
      method: 'POST',
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          const content = response.data.content;
          if (content && content.length > 0) {
            content.forEach(function(item) {
              if (item.avatarUrl && item.avatarUrl.indexOf(baseUrl) >= 0) {
                item.avatarUrl += '?number=' + Math.random();
              }
            });
          }
          that.setData({
            coachList: content
          });
        } else {
          wx.showToast({
            title: '获取教练列表出错',
            icon: 'none'
          })
        }
      }
    });
  },
  onShow: function() {
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              app.globalData.userInfo = res.userInfo;
              that.setData({
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    });
  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      app.globalData.userInfo = e.detail.userInfo;
      this.setData({
        isShow: false
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '提示',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {}
      });
    }
  },
  toTrain: function() {
    const openId = app.globalData.openId;
    const url = app.globalData.url;
    wx.request({
      url: url + '/train/getPhoneByOpenId/' + openId,
      success: function(response) {
        if (response.data.success) {
          const phone = response.data.content;
          wx.setStorageSync("traineePhone", phone);
          wx.navigateTo({
            url: '/pages/trainModule/trainModule',
          })
        }
      }
    });
  },
  makePhone: function() {
    wx.makePhoneCall({
      phoneNumber: '88888888'
    })
  },
  toCoach: function() {
    wx.switchTab({
      url: '/pages/coach/coach',
    })
  },
  toEmsTech: function() {
    wx.navigateTo({
      url: '/pages/emsTech/emsTech'
    })
  },
  toDetail: function(e) {
    const index = e.currentTarget.dataset.index;
    const openId = this.data.coachList[index].openId;
    wx.setStorageSync("openId", openId);
    wx.navigateTo({
      url: '/pages/detail/detail',
    })
  },
  openMap: function() {
    const latitude = 22.573833;
    const longitude = 113.949165;
    const lnglat = this.bd09togcj02(longitude, latitude);
    wx.openLocation({
      latitude: lnglat[1],
      longitude: lnglat[0],
      scale: 16
    });
  },
  bd09togcj02: function(bd_lon, bd_lat) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;　　
    var x = bd_lon - 0.0065;　　
    var y = bd_lat - 0.006;　　
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);　　
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);　　
    var gg_lng = z * Math.cos(theta);　　
    var gg_lat = z * Math.sin(theta);　　
    return [gg_lng, gg_lat];
  },
  toBook: function() {
    wx.navigateTo({
      url: '/pages/bookToCompany/bookToCompany',
    })
  },
  onPullDownRefresh: function() {
    this.getCoach();
    this.getClub();
  },
  getClub: function() {
    wx.showNavigationBarLoading();
    const url = app.globalData.url;
    const that = this
    wx.request({
      url: url + '/management/getClub',
      data: {
        companyName
      },
      method: 'POST',
      success: function(response) {
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
        if (response.data.success) {
          const clubPictures = [];
          const trainPictures = [];
          const obj = response.data.content;
          if (obj.clubPictures && obj.clubPictures.length > 0) {
            obj.clubPictures.forEach(function(item) {
              clubPictures.push(item.filePath + '?number=' + Math.random());
            });
          }
          if (obj.trainPictures && obj.trainPictures.length > 0) {
            obj.trainPictures.forEach(function(item) {
              trainPictures.push(item.filePath + '?number=' + Math.random());
            });
          }
          that.setData({
            imgUrls: clubPictures,
            imgUrls2: trainPictures
          });
        } else {
          wx.showToast({
            title: response.data.message,
            icon: 'none'
          })
        }
      }
    })
  }
})